# -*- coding: utf-8 -*-

import cgi, os
import hashlib,logging

from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import memcache

from gaesessions import get_current_session
from db import Thread, User

def get_data(name):
	data = memcache.get(name)
	if data is not None:
		return data
	else:
		data = {}
		him = User.all().filter('name', name).get()
		if him and him.extPass:
			data['extPass'] = him.extPass
		data['nber'] = ( Thread.all()
						.filter('destin IN', (name, name.lower())) 
						.filter('stateIn', 0).count()  )
		memcache.add(name, data, 86600)
		return data


class status(webapp.RequestHandler):
	def get(self, lang, pseudo):
#		self.error(410)
#		return
		if lang not in ('json', 'xml'):
			self.error(404)
			return False
		
		d = get_data(pseudo)
		if 'extPass' in d:
			m = hashlib.md5()
			m.update(self.request.get('pass'))
			if d['extPass'] != m.hexdigest():
				self.error(409)
				return False

		template_values = {
				'nberThreadNotRead': d['nber'],
				}
		path = os.path.join(os.path.dirname(__file__), 'out/status.%s'%lang)
		self.response.headers.add_header('Access-Control-Allow-Origin', '*')
		self.response.out.write(template.render(path, template_values))
